#include "epoll.h"
#include <sys/epoll.h>
#include "main.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include "mqtt.h"
#include "link.h"
using namespace std;
void epoll_deal(int epfd,int sockfd)
{
     epoll_event events[EVENTNUM]={0};  
     int readynum=0;
      struct sockaddr client_info;
      socklen_t len=sizeof(client_info);
      epoll_event ev;
      char buffer[128]={0};
  while(1)
  {
    //cout<<"我在等"<<endl;
    readynum=epoll_wait(epfd,events,EVENTNUM,-1);
    if(readynum==-1)
    {

     cout<<"epoll wait fail..."<<endl;
     continue;

    }
    
    for(int i=0;i<EVENTNUM;i++)
    {
        if(events[i].data.fd==sockfd)
        {
 
           int fd=accept(sockfd,&client_info,&len);
           if(fd==-1)
           {

              cout<<"accept fail..."<<endl;

           }

           cout<<"服务端接收连接"<<endl;

           ev.data.fd=fd;
           ev.events=EPOLLIN;

     int ret=epoll_ctl(epfd,EPOLL_CTL_ADD,fd,&ev);   
     if(ret==-1)
     {cout<<"epoll_ctl fail..."<<endl;}

        }
        else
        { memset(buffer,0,sizeof(buffer));
          int n=recv(events[i].data.fd,buffer,sizeof(buffer),0);
          if(n<0)
          {
              // cout<<"recv fail ..."<<endl;


          }
          else if(n==0)
          {

              cout<<"客户端 下线"<<events[i].data.fd<<endl;
                int ret=epoll_ctl(epfd,EPOLL_CTL_DEL,events[i].data.fd,&events[i]);   
                  if(ret==-1)
                     {cout<<"epoll_ctl fail..."<<endl;}                
              // close(events[i].data.fd);

                // delete_link(events[i].data.fd);




          }
          else
          {   //收到客户端的请求
              int type=parse_type(buffer[0]);
             

             switch(type)
             {
              case CONNECT:
              mqtt_connect(events[i].data.fd,buffer);
              break;
              case PUBLISH:
              mqtt_publish(events[i].data.fd,buffer);
              break;
              case SUBSCRIBE:
              mqtt_subscribe(events[i].data.fd,buffer);
              break;
              case REGISTER:
              mqtt_register(events[i].data.fd,buffer);
              break;
              case LOGIN:
              mqtt_login(events[i].data.fd,buffer);
              break;









             }





          }


        }


    }

  }

}
void epoll_handle(int sockfd)
{
 // epoll_event events[EVENTNUM];
  int epfd=epoll_create(5);
  if(epfd<0)
  {
      cout<<"epoll create fail...."<<endl;

  }
     cout<<"epoll create seuess...."<<endl;

     epoll_event ev;
     ev.data.fd=sockfd;
     ev.events=EPOLLIN;

     int ret=epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&ev);
     if(ret<0)
     {cout<<"epoll_ctl fail..."<<endl;}
 
    


    epoll_deal(epfd,sockfd);

}